//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 李振兴 on 15/10/17.
//  Copyright © 2015年 李振兴. All rights reserved.
//

import Foundation

class UserAccountViewModel {
    //单例
    static let sharedUserAccount = UserAccountViewModel()
    
    var account:UserAccount?
    
    var isLogon:Bool{
        return account?.access_token != nil && !isExpired
    }
    //计算型属性
    private var accountPath:String{
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
            .UserDomainMask, true).last!
        path = (path as NSString).stringByAppendingPathComponent("userAccount.plist")
        //print("path:\(path)")
        return path
    }
     var accessToken:String?{
        if !isExpired {
            return account?.access_token
        }
        return nil
    }
    private var isExpired:Bool{
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //没过期
            return false
        }
        return true
    }
    /// 用户头像 URL
    var avatarUrl: NSURL {
        return NSURL(string: account?.avatar_large ?? "")!
    }
    //加private 后外部只能通过单例常量访问，而不能通过（）
    private init(){
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        if isExpired {
            account = nil
        }
        //print(account)
    }
    
}
// MARK: - 用户账户相关的网络方法
extension UserAccountViewModel{
    //MARK:获取AccessToken
    func loadAccessToken(code: String,finished:(isSuccess:Bool)->()){
        NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil {
                finished(isSuccess: false)
            }
            self.account = UserAccount(dict: result as! [String: AnyObject])
            
            self.loadUserInfo(self.account!, finished: finished)
            
        }
    
    }
    
    private func loadUserInfo(account: UserAccount, finished: (isSuccessed: Bool)->()){
        NetWorkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            if error != nil {
                
                print("加载用户出错了")
                
                finished(isSuccessed: false)
                return
            }
            
            // 提示：如果使用 if let / guard let 统统使用 `?`
            // 作了两个判断
            // 1. result 一定有内容
            // 2. 一定是字典
            guard let dict = result as? [String: AnyObject] else {
                print("格式错误")
                
                finished(isSuccessed: false)
                return
            }
            
            // dict 一定是一个有值的字典
            // 将用户信息保存
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            // 保存对象 － 会调用对象的 encodeWithCoder 方法
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            
            // 需要完成回调!!!
            finished(isSuccessed: true)
        }
        
    }


}